package crontab

import (
	"context"
	"fmt"
	"strings"
	"time"
	"wx-uniapp-go/internal/repository/models"
)

type CouponTask struct{}

// HandleExpiredCoupons 处理过期优惠券
func (t *CouponTask) HandleExpiredCoupons() {
	ctx := context.Background()
	now := time.Now()
	batchSize := 100 // 每次处理的批次大小

	for {
		// 查询未处理的过期优惠券
		var coupons []*models.UserCoupon
		where := "status = ? AND valid_end < ?"
		_, err := models.FindByPage(ctx, &coupons, 1, batchSize, where,
			models.CouponStatusUnused, now)
		if err != nil {
			fmt.Printf("查询过期优惠券失败: %v\n", err)
			return
		}

		// 如果没有需要处理的数据，退出循环
		if len(coupons) == 0 {
			break
		}

		// 批量更新状态
		couponIds := make([]int64, len(coupons))
		for i, coupon := range coupons {
			couponIds[i] = coupon.Id
		}

		// 开启事务
		ctx = models.BeginTransaction(ctx)

		// 更新优惠券状态
		err = t.batchUpdateStatus(ctx, couponIds)
		if err != nil {
			fmt.Printf("更新优惠券状态失败: %v\n", err)
			return
		}

		// 批量插入日志
		err = t.batchInsertLogs(ctx, couponIds)
		if err != nil {
			fmt.Printf("插入优惠券日志失败: %v\n", err)
			return
		}

		fmt.Printf("成功处理 %d 张过期优惠券\n", len(coupons))
	}
}

// batchUpdateStatus 批量更新优惠券状态
func (t *CouponTask) batchUpdateStatus(ctx context.Context, couponIds []int64) error {
	if len(couponIds) == 0 {
		return nil
	}

	// 构建IN查询条件
	where := fmt.Sprintf("id IN (%s)", buildInParams(couponIds))

	// 更新状态为已过期
	coupon := &models.UserCoupon{
		Status: models.CouponStatusExpired,
	}

	return models.BatchUpdateByIds(ctx, where, coupon, convertToInterface(couponIds))
}

// batchInsertLogs 批量插入过期日志
func (t *CouponTask) batchInsertLogs(ctx context.Context, couponIds []int64) error {
	if len(couponIds) == 0 {
		return nil
	}

	// 查询优惠券信息
	var coupons []*models.UserCoupon
	where := fmt.Sprintf("id IN (%s)", buildInParams(couponIds))
	err := models.Find(ctx, &coupons, where, convertToInterface(couponIds)...)
	if err != nil {
		return err
	}

	// 构建日志记录
	logs := make([]*models.CouponLog, len(coupons))
	for i, coupon := range coupons {
		logs[i] = &models.CouponLog{
			UserId:   coupon.UserId,
			CouponId: coupon.Id,
			Type:     models.CouponLogTypeExpire,
			Remark:   "优惠券过期",
		}
	}

	// 批量插入日志
	_, err = models.BatchInsert(ctx, logs)
	return err
}

// buildInParams 构建IN查询参数
func buildInParams(ids []int64) string {
	params := make([]string, len(ids))
	for i := range ids {
		params[i] = "?"
	}
	return strings.Join(params, ",")
}

// convertToInterface 转换为interface切片
func convertToInterface(ids []int64) []interface{} {
	params := make([]interface{}, len(ids))
	for i, id := range ids {
		params[i] = id
	}
	return params
}
